package com.zhuyuan.getaway.filter;

import com.zhuyuan.core.constant.Oauth2Constants;
import com.zhuyuan.core.enums.ResultCodeEnum;
import com.zhuyuan.core.util.ServletUtils;
import com.zhuyuan.core.util.TokenUtils;
import com.zhuyuan.getaway.config.properties.GatewaySecurityProperties;
import com.zhuyuan.redis.RedisService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;


/**
 * @Author: 张琳凯
 * @Description: TODO
 * @DateTime: 2025/1/6 20:47
 **/
@Component
@Slf4j
public class GatewayFilterConfig implements GlobalFilter, Ordered {

    @Resource
    private RedisService redisService;
    @Resource
    private GatewaySecurityProperties gatewaySecurityProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        String requestUrl = exchange.getRequest().getPath().value();
        //-------------
        // 获得路由
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        // 配置文件中配置的route的uri属性(匹配到的route),本例中是http://127.0.0.1:8001
        String uri = route.getUri().toString();
        ServerHttpRequest request = exchange.getRequest();
        // 请求路径中域名之后的部分,本例中是/api/name/get
        String path = request.getPath().toString();
        //-------------
        //1 过滤白名单
        if (isRelease(requestUrl)) {
            return chain.filter(exchange);
        }
        //2 检查token是否存在
        String token = exchange.getRequest().getHeaders().getFirst(Oauth2Constants.HEADER_TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            log.error("没有携带Token信息！");
            return ServletUtils.webFluxResponseWriter(response, ResultCodeEnum.INVALID_TOKEN);
        }
        //3 去除前缀的token
        String tokenNoHead = TokenUtils.getToken(token);
        //4 判断是否是有效的token
        Claims claims = TokenUtils.parseToken(tokenNoHead);
        if (claims == null) {
            return ServletUtils.webFluxResponseWriter(response, ResultCodeEnum.INVALID_TOKEN);
        }
//        //5 判断redis是否存在该token,这个key的标志是RedisTokenStore中设置的，所以没换
//        Boolean hasTokenOfRedis = redisService.hasKey("auth:"+tokenNoHead);
//        log.debug("查询token是否存在: {}", hasTokenOfRedis);
//        if (!hasTokenOfRedis) {
//            return ServletUtils.webFluxResponseWriter(response, ResultCodeEnum.UNAUTHORIZED);
//        }
        return chain.filter(exchange);
    }
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 根据白名单，判断是否放行
     */
    private boolean isRelease(String path) {
        AntPathMatcher pathMatcher = new AntPathMatcher();
        return gatewaySecurityProperties.getIgnoreUrls().stream()
                .anyMatch(url->pathMatcher.match(url,path));
    }
}
